//
//  FriendsInfoViewController.m
//  AAIM
//
//  Created by awh on 2019/11/29.
//  Copyright © 2019年 AAIM. All rights reserved.
//

#import "FriendsInfoViewController.h"

#import "XLPopMenuViewSingleton.h"
#import "XLPopMenuViewModel.h"
#import "CommonGroupViewController.h"

#import "ContactRequestLogic.h"
#import "ChatViewController.h"
#import "ContactModel.h"

#import "UserInfoViewController.h"
#import "ChangeNickNameViewController.h"
#import "ReportViewController.h"

@interface FriendsInfoViewController ()<ChangeVCDelegate>
@property(nonatomic,strong)UIScrollView * bgScrollView;
@property(nonatomic,strong)UIImageView * headImage;
@property(nonatomic,strong)UILabel * friendName;
@property(nonatomic,strong)UILabel * friendAccount;
@property(nonatomic,strong)UILabel * friendID;
@property(nonatomic,strong)UILabel * friendSign;
@property(nonatomic,strong)UIView * line;
@property(nonatomic,strong)UIButton * sendButton;
@property(nonatomic,strong)CustomAlertView * deleteAlert;
@property(nonatomic,strong)CustomAlertView * sendAddFriendAlert;
@property(nonatomic,strong)ContactModel * model;
@property(nonatomic,strong)NSMutableArray * dataAry;
@property (nonatomic,strong) UserModel * userModel;
@end

@implementation FriendsInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addSubViews];
    [self requestFriendInfoData];
    
}

- (void)requestFriendInfoData{
    [self showAlwaysTipHudWithText:@"加载中，请稍等"];
    if ([_type isEqualToString:@"friend"]) {
        [RequestData GetUserInfoWithToken:[LoginManager shareLoginManager].userModel.token userUUid:[LoginManager shareLoginManager].userModel.uuid fuuid:_Fuuid Success:^(NSDictionary * _Nonnull Dict) {
            NSLog(@"%@",Dict);
            KWeakSelf;
            [weakSelf hideHud];
            weakSelf.model = [ContactModel mj_objectWithKeyValues:Dict[@"data"]];
            weakSelf.userModel = [UserModel mj_objectWithKeyValues:Dict[@"data"]];
            [weakSelf.dataAry addObject:weakSelf.model];
            weakSelf.isFriend = [weakSelf.model.isFriend integerValue];
            weakSelf.friendSign.text = weakSelf.model.remark;
             weakSelf.friendID.text = [NSString stringWithFormat:@"ID：%@",weakSelf.model.fuuid];
//              weakSelf.friendAccount.text = [NSString stringWithFormat:@"账号：%@",weakSelf.model.userName.length == 0?weakSelf.model.name:weakSelf.model.userName];
              weakSelf.friendName.text = weakSelf.model.nickname;
              NSString * headUrl = weakSelf.model.head;
              [weakSelf.headImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,headUrl]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                  KWeakSelf;
                  if (!error) {
                      weakSelf.headImage.image = image;
                  }else
                  {
                      weakSelf.headImage.image = kHeadPlaceholderImage;
                  }
              }];
              PublicButton * btn = [self.view viewWithTag:1];
              btn.remarkLbl.text = weakSelf.model.fremark;
              PublicButton * describeBtn = [self.view viewWithTag:2];
            if (weakSelf.model.describe) {
                describeBtn.remarkLbl.text = weakSelf.model.describe;
            }else{
                describeBtn.remarkLbl.text = @"暂时没有任何描述";
            }
            
        } failure:^(NSString * _Nonnull errMsg) {
            [self showTipHudWithText:errMsg];
        }];
    }else{
        [ContactRequestLogic requestSearchFriendResultsWithfuuid:_Fuuid Success:^(NSDictionary * _Nonnull Dict){
            NSLog(@"%@",Dict);
            KWeakSelf;
            [weakSelf hideHud];
                weakSelf.model = [ContactModel mj_objectWithKeyValues:Dict[@"data"]];
             weakSelf.userModel = [UserModel mj_objectWithKeyValues:Dict[@"data"]];
                [weakSelf.dataAry addObject:weakSelf.model];
                weakSelf.isFriend = [weakSelf.model.isFriend integerValue];
          weakSelf.friendSign.text = weakSelf.model.remark;
           weakSelf.friendID.text = [NSString stringWithFormat:@"ID：%@",weakSelf.model.fuuid];
//            weakSelf.friendAccount.text = [NSString stringWithFormat:@"账号：%@",weakSelf.model.userName.length == 0?weakSelf.model.name:weakSelf.model.userName];
            weakSelf.friendName.text = weakSelf.model.nickname;
            NSString * headUrl = weakSelf.model.head;
            [weakSelf.headImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,headUrl]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                KWeakSelf;
                if (!error) {
                    weakSelf.headImage.image = image;
                }else
                {
                    weakSelf.headImage.image = kHeadPlaceholderImage;
                }
            }];
            PublicButton * btn = [self.view viewWithTag:1];
            btn.remarkLbl.text = weakSelf.model.fremark;
            PublicButton * describeBtn = [self.view viewWithTag:3];
            if (weakSelf.model.describe) {
                  describeBtn.remarkLbl.text = weakSelf.model.describe;
            }else{
                describeBtn.remarkLbl.text = @"暂时没有任何描述";
            }
            
            [weakSelf.sendButton setTitle:weakSelf.isFriend==YES?@"发消息":@"加好友" forState:UIControlStateNormal];
        } failure:^(NSString * _Nonnull errMsg) {
            [self showTipHudWithText:errMsg];
        }];
    }
    
}

-(void)addSubViews
{
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setImage:[UIImage imageNamed:@"icon- 点点"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBtnDidClickAction:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn sizeToFit];
    rightBtn.frame = CGRectMake(0, 0, 44, 44);
    rightBtn.jk_touchAreaInsets  = UIEdgeInsetsMake(10, 10, 10, 10);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.gk_navigationItem.rightBarButtonItems = @[rightItem];
    
    [self.view addSubview:self.bgScrollView];
    [self.bgScrollView addSubview:self.headImage];
    [self.bgScrollView addSubview:self.friendName];
//    [self.bgScrollView addSubview:self.friendAccount];
    [self.bgScrollView addSubview:self.friendID];
    [self.bgScrollView addSubview:self.friendSign];
    [self.bgScrollView addSubview:self.line];
    
    _friendID.text = [NSString stringWithFormat:@"ID：%@",_model.fuuid];
//    _friendAccount.text = [NSString stringWithFormat:@"账号：%@",_model.userName.length == 0?_model.name:_model.userName];
    _friendName.text = _model.nickname;
    NSString * headUrl = _model.head;
    [_headImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",userHeaderImage,headUrl]] placeholderImage:[UIImage imageNamed:@"bg_pyqtx"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        KWeakSelf;
        if (!error) {
            weakSelf.headImage.image = image;
        }else
        {
            weakSelf.headImage.image = kHeadPlaceholderImage;
        }
    }];
    _friendSign.text = _model.remark;
    
    NSArray * titleArray=@[@"备注",@"共同群组",@"描述"];
    for (int i=0; i<3; i++) {
        PublicButton * btn =[[PublicButton alloc]initWithFrame:CGRectMake(_headImage.x, _line.bottom+(55+0)*i, SCREEN_WIDTH-30, 55) withButtonType:@"FriendInfoVCButton"];
        btn.titleLbl.text=titleArray[i];
        if (i==0) {
            btn.height=80;
            btn.remarkLbl.frame=CGRectMake(btn.titleLbl.x+btn.titleLabel.width+50.f, btn.titleLbl.y, btn.width-btn.titleLabel.width-80.f, 20);
            
            if (_model.fremark) {
                btn.remarkLbl.text=_model.fremark;
            }else{
                btn.remarkLbl.text=@"";
            }
            
            btn.remarkLbl.textAlignment=2;
            btn.remarkLbl.font=[UIFont systemFontOfSize:15];
            btn.remarkLbl.textColor=KHEXCOLOR(@"#262B2F");
        }
        if (i==2) {
            btn.height=80;
            btn.remarkLbl.frame=CGRectMake(btn.titleLbl.x, btn.titleLbl.bottom+10, btn.width, 20);
            if (_model.describe) {
                btn.remarkLbl.text=_model.describe;
            }else{
                btn.remarkLbl.text=@"暂时没有任何描述";
            }
            btn.rigthImage.hidden = YES;
            btn.remarkLbl.textAlignment=0;
            btn.remarkLbl.font=[UIFont systemFontOfSize:13];
            btn.remarkLbl.textColor=KHEXCOLOR(@"#AFAFAF");
            btn.lineV.y=btn.height-0.5;
        }
        
        [btn addTarget:self action:@selector(touchActive:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag=i+1;
        [self.bgScrollView addSubview:btn];
    }
    [self.bgScrollView addSubview:self.sendButton];
    
}

-(void)changeWithStr:(NSString *)text withIndex:(NSInteger)index{
//    if (index == 7) {
//        [[UserDataBaseTool shareUserDataBaseTool] reloadData:1 Success:^(BOOL isOK) {
//            if (isOK) {
//                [[NSNotificationCenter defaultCenter] postNotificationName:kMessageSystemAddFriends object:nil];
//            }
//        }];
//    }else{
////       PublicButton * btn = [self.view viewWithTag:3];
////        btn.remarkLbl.text = text;
//    }
    [self requestFriendInfoData];
}

- (void)touchActive:(PublicButton *)sender{
    switch (sender.tag) {
        case 1:
        {
            ChangeNickNameViewController * changeVC = [[ChangeNickNameViewController alloc]init];
            changeVC.index = 7;
            changeVC.fuuid = _Fuuid;
            changeVC.delegate = self;
            changeVC.contentStr = sender.remarkLbl.text;
            changeVC.pageType = @"friendInfo";
            changeVC.model = _userModel;
            [self.navigationController pushViewController:changeVC animated:YES];
        }
            break;
        case 2:
        {
            NSLog(@"公共群组");
            CommonGroupViewController * CGVC = [[CommonGroupViewController alloc]init];
            CGVC.Fuuid=_Fuuid;
            [self.navigationController pushViewController:CGVC animated:YES];
        }
            break;
        case 3:
        {
            ChangeNickNameViewController * changeVC = [[ChangeNickNameViewController alloc]init];
            changeVC.fuuid = _Fuuid;
            changeVC.delegate = self;
            changeVC.index = 8;
            changeVC.contentStr = sender.remarkLbl.text;
            changeVC.pageType = @"friendInfo";
            changeVC.model = _userModel;
            [self.navigationController pushViewController:changeVC animated:YES];
        }
            break;
        default:
            break;
    }}

-(UIScrollView*)bgScrollView
{
    if (!_bgScrollView) {
        _bgScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0,NavigationBarHeight, SCREEN_WIDTH,SCREEN_HEIGHT-NavigationBarHeight)];
        _bgScrollView.showsVerticalScrollIndicator=NO;
        _bgScrollView.showsHorizontalScrollIndicator=NO;
        _bgScrollView.backgroundColor=[UIColor whiteColor];
        [_bgScrollView setContentSize:CGSizeMake(0, kScreenHeight)];
    }
    return _bgScrollView;
}
-(UIImageView*)headImage
{
    if (!_headImage) {
        _headImage=[[UIImageView alloc]initWithFrame:CGRectMake(15, 25, 70, 70)];
        _headImage.layer.masksToBounds=YES;
        _headImage.layer.cornerRadius=35;
        _headImage.backgroundColor=[UIColor whiteColor];
        //        [_headImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",MainImageURl,[LoginManager shareLoginManager].userModel.avatar]] placeholderImage:kHeadPlaceholderImage];
    }
    return _headImage;
}
-(UILabel*)friendName
{
    if (!_friendName) {
        _friendName=[self CreateLabelWithFrame:CGRectMake(_headImage.right+15, _headImage.y+18, SCREEN_WIDTH-_headImage.right-30, 18) Font:15 titleColor:KHEXCOLOR(@"#262B2F")];
        _friendName.text=@"刚女孩";
    }
    return _friendName;
}
-(UILabel*)friendAccount
{
    if (!_friendAccount) {
        _friendAccount=[self CreateLabelWithFrame:CGRectMake(_friendName.x, _friendName.bottom+3, _friendName.width, _friendName.height) Font:12 titleColor:KHEXCOLOR(@"#AFAFAF")];
        _friendAccount.text=@"账号：39282131";
    }
    return _friendAccount;
}
-(UILabel*)friendID
{
    if (!_friendID) {
        _friendID=[self CreateLabelWithFrame:CGRectMake(_friendName.x, _friendName.bottom+8, _friendName.width, _friendName.height) Font:12 titleColor:KHEXCOLOR(@"#AFAFAF")];
        _friendID.text=@"ID：392822";
    }
    return _friendID;
}
-(UILabel*)friendSign
{
    if (!_friendSign) {
        _friendSign=[self CreateLabelWithFrame:CGRectMake(_headImage.x, _headImage.bottom+15, SCREEN_WIDTH-30,20) Font:13 titleColor:KHEXCOLOR(@"#AFAFAF")];
        _friendSign.text=@"签名：这个同学很懒，什么都没留下…";
    }
    return _friendSign;
}
-(UILabel*)CreateLabelWithFrame:(CGRect)Frame Font:(CGFloat)font titleColor:(UIColor*)titleColor
{
    UILabel * lbl=[[UILabel alloc]initWithFrame:Frame];
    lbl.font=[UIFont systemFontOfSize:font];
    lbl.textColor=titleColor;
    return lbl;
}
-(UIView*)line
{
    if (!_line) {
        _line=[[UIView alloc]initWithFrame:CGRectMake(_friendSign.x, _friendSign.bottom+15, _friendSign.width, 0.5)];
        _line.backgroundColor=KHEXCOLOR(IM_Color_SeparateLine);
    }
    return _line;
}

-(UIButton*)sendButton
{
    if (!_sendButton) {
        PublicButton*btn=[self.view viewWithTag:3];
        _sendButton=[UIButton buttonWithType:UIButtonTypeCustom];
        _sendButton.frame=CGRectMake(_headImage.x, btn.bottom+50, SCREEN_WIDTH-30, 40);
        _sendButton.backgroundColor=KHEXCOLOR(AllBackColor_bule);
        _sendButton.layer.masksToBounds=YES;
        _sendButton.layer.cornerRadius = 5;
        [_sendButton setTitle:_isFriend==YES?@"发消息":@"加好友" forState:UIControlStateNormal];
        [_sendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _sendButton.titleLabel.font=[UIFont systemFontOfSize:15];
        [_sendButton addTarget:self action:@selector(didButtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendButton;
}
-(void)didButtnAction:(UIButton*)sender
{
    
    KWeakSelf;
    if (_isFriend) {
        //是好友跳转聊天界面
        ChatViewController * chatVC= [[ChatViewController alloc]init];
        chatVC.chatType=ChatTypeFriend;
        chatVC.receiverId=_Fuuid;
        chatVC.gk_navTitle=_friendName.text;
        [self.navigationController pushViewController:chatVC animated:YES];
    }else
    {
        _sendAddFriendAlert=[[CustomAlertView alloc]initWithFrame:self.view.bounds withType:@"8" title:[LoginManager shareLoginManager].userModel.userName];
        
        _sendAddFriendAlert.clickBlock = ^(NSString * _Nonnull selectType, NSString * _Nonnull textf, NSString * _Nonnull remarkStr) {
            if ([selectType isEqualToString:@"2"]) {
                
                //source ，s 搜索  g群
                [ContactRequestLogic  requestAddFriendWithContent:textf fuuid:weakSelf.model.fuuid groupid:@"" source:@"s" Success:^(NSDictionary * _Nonnull Dict) {
                    
                    //申请成功发送im消息
                    NSLog(@"发送请求%@",Dict);
                    
                    
                    if ([Dict[@"code"] integerValue] == 200) {
                        if (![CommonTools isNull:Dict key:@"data"]) {
                            NSString * addStatu = [NSString stringWithFormat:@"%@",Dict[@"data"][@"add"]];
                            if ([addStatu isEqualToString:@"1"]) {
                                [[UserDataBaseTool shareUserDataBaseTool] reloadData:1 Success:^(BOOL isOK) {
                                    if (isOK) {
                                        [[NSNotificationCenter defaultCenter] postNotificationName:kMessageSystemAddFriends object:nil];
                                    }
                                    
                                }];
                                weakSelf.isFriend = YES;
                                [weakSelf.sendButton setTitle:@"发消息" forState:UIControlStateNormal];
                            }
                            [weakSelf showTipHudWithText:@"已添加对方为好友"];
                        }else{
                            [weakSelf showTipHudWithText:Dict[@"message"]];
                        }
                    }
                    
                } failure:^(NSString * _Nonnull errMsg) {
                    [weakSelf showTipHudWithText:errMsg];
                }];
            }
            [weakSelf.sendAddFriendAlert removeFromSuperview];
        };
        [[UIApplication sharedApplication].keyWindow addSubview:_sendAddFriendAlert];
    }
}

-(void)rightBtnDidClickAction:(UIButton*)sender
{
    KWeakSelf;
    
    XLPopMenuViewModel * userinfoModel =[[XLPopMenuViewModel alloc]init];
    userinfoModel.image=@"icon-个人资料";
    userinfoModel.title=@"个人资料";
//
//    XLPopMenuViewModel * shareBusinessCardModel =[[XLPopMenuViewModel alloc]init];
//    shareBusinessCardModel.image=@"icon-口令进群";
//    shareBusinessCardModel.title=@"分享名片";
    
    XLPopMenuViewModel * reportModel =[[XLPopMenuViewModel alloc]init];
    reportModel.image=@"icon-举报";
    reportModel.title=@"举报";
    
    XLPopMenuViewModel * deleteModel =[[XLPopMenuViewModel alloc]init];
    deleteModel.image=@"icon-删除好友";
    deleteModel.title=@"删除好友";
    
    NSArray *popItems;
    if (_isFriend) {
        popItems = @[userinfoModel,reportModel,deleteModel];
    }else
    {
        popItems = @[userinfoModel,reportModel];
    }
    // 弹出框的宽度
    CGFloat menuViewWidth = 150;
    // 弹出框的左上角起点坐标
    CGFloat y = IS_iPhoneX ? 88  : 64 ;
    CGPoint startPoint = CGPointMake([UIScreen mainScreen].bounds.size.width - menuViewWidth - 10, y);
    [[XLPopMenuViewSingleton shareManager] creatPopMenuWithFrame:startPoint popMenuWidth:menuViewWidth popMenuItems:popItems action:^(NSInteger index) {
        if ([LoginManager shareLoginManager].userModel.allow.integerValue == 1) {
            [self showTipHudWithText:@"无权限"];
            return;
        }
        if(index==0){
            NSLog(@"个人资料");
            UserInfoViewController * infoVC = [[UserInfoViewController alloc]init];
            infoVC.fuuid = weakSelf.model.fuuid;
            infoVC.index = 1;
            [self.navigationController pushViewController:infoVC animated:YES];
        }
//        else if(index==1)
//        {
//            NSLog(@"分享名片");
//
//
//        }
        else if(index==1)
        {
            NSLog(@"举报");
            ReportViewController * reportVC = [[ReportViewController alloc]init];
            reportVC.fuuid = weakSelf.Fuuid;
            reportVC.reportType = @"friend";
            [self.navigationController pushViewController:reportVC animated:YES];
        }else if(index==2)
        {
            NSLog(@"删除好友");
            weakSelf.deleteAlert=[[CustomAlertView alloc]initWithFrame:self.view.bounds withType:@"7" title:@"是否确定删除好友"];
            weakSelf.deleteAlert.clickBlock = ^(NSString * _Nonnull selectType, NSString * _Nonnull textf, NSString * _Nonnull remarkStr) {
                
                if ([selectType isEqualToString:@"2"]) {
                    
                    [ContactRequestLogic requestDeleteFriendWithFuuid:weakSelf.Fuuid Success:^(NSDictionary * _Nonnull Dict) {
                        NSLog(@"删除好友成功，返回上一页 ，删除本地好友，本地聊天记录");
                        
//                         [[UserDataBaseTool shareUserDataBaseTool] deleteFriend:weakSelf.Fuuid];
//                        删除聊天记录
                        [[ChatMessagesDataBase shareChatMessagesDataBase] clearAllMessagesWithUid:[self.Fuuid integerValue]];
                        //        删除会话记录
                        [[ConversationListDataBase shareConversationListDataBase] deleteConversationWithKeyid:[NSString stringWithFormat:@"friend_%@",self.Fuuid]];
                        [[ConversationManager shareManager] deleteConversationWithKeyid:[NSString stringWithFormat:@"friend_%@",self.Fuuid]];
                        [[ConversationManager shareManager] reloadData];
                        //       发通知 刷新首页数据
//                         [[NSNotificationCenter defaultCenter] postNotificationName:cChatRecordMessage object:nil];
                        [[UserDataBaseTool shareUserDataBaseTool] reloadData:1 Success:^(BOOL isOK) {
                            if (isOK) {
                                [[NSNotificationCenter defaultCenter] postNotificationName:kMessageSystemAddFriends object:nil];
                            }
                        }];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                           [weakSelf.navigationController popViewControllerAnimated:YES];
                        });
                       
                    } failure:^(NSString * _Nonnull errMsg) {
                        [weakSelf showTipHudWithText:errMsg];
                    }];
                    
                }
                [weakSelf.deleteAlert removeFromSuperview];
            };
            [[UIApplication sharedApplication].keyWindow addSubview:weakSelf.deleteAlert];
        }
    }];
    
    
}

-(NSMutableArray *)dataAry{
    if (!_dataAry) {
        _dataAry = [NSMutableArray array];
    }
    return _dataAry;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
